package com.karry.yl.web.system;


import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.karry.commons.AliMsg;
import com.karry.commons.Constants;
import com.karry.commons.base.SuperController;
import com.karry.commons.util.NumberUtil;
import com.karry.commons.vo.JsonResponse;
import com.karry.commons.web.ExceptionController;
import com.karry.yl.domain.baseinfo.Enterprise;
import com.karry.yl.domain.baseinfo.MinfeiUnits;
import com.karry.yl.domain.baseinfo.Organization;
import com.karry.yl.domain.mz.MzDepartment;
import com.karry.yl.domain.system.User;
import com.karry.yl.service.baseinfo.EnterpriseService;
import com.karry.yl.service.baseinfo.MinfeiUnitsService;
import com.karry.yl.service.baseinfo.OrganizationService;
import com.karry.yl.service.mz.MzDepartmentService;
import com.karry.yl.service.system.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * 说明 : 注册控制层
 *
 * @author 于瑞智
 * @version 1.0.0
 * @dateTime 2017年7月12日 下午5:18:12
 */
@Controller
@RequestMapping("/register")
public class RegisterController extends SuperController {

    private static Logger log = LoggerFactory.getLogger(ExceptionController.class);  //日志记录
    @Autowired
    private UserService userService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private MinfeiUnitsService minfeiUnitsService;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private MzDepartmentService mzDepartmentService;

    @RequestMapping
    public String registerUI(ModelMap map) {
        List<MzDepartment> mzDepartments = mzDepartmentService.selectList();
        map.put("mzDepartments",mzDepartments);
        return "register";
    }


    /**
     * 发送短信异步接口
     *
     * @param phone
     * @return
     */
    @RequestMapping("/sendMsg")
    @ResponseBody
    public JsonResponse sendMsg(String phone, HttpSession session) {
        JsonResponse rs = JsonResponse.fail("发送失败！");
        if (null == phone || phone.isEmpty()) {
            rs = JsonResponse.fail("请输入手机号码！");
        } else {
            User u = userService.selectOne(new EntityWrapper<User>().eq("phone", phone).eq("deleted", false));
            if (null != u) {
                rs = JsonResponse.fail("手机号已被注册！");
            } else {
                try {
                    int code = NumberUtil.getRandomInt(Constants.PHONE_VCODE_LEN);
                    AliMsg.send(phone, code, AliMsg.TEMPLATE_CODE, AliMsg.SIGN_NAME);
                    rs = JsonResponse.success("发送成功！");
                    session.setAttribute(Constants.SK_REGIST_PHONE_CODE_KEY, code);
                    session.setAttribute(Constants.SK_REGIST_PHONE_CODE_KEY_DATE, System.currentTimeMillis());
                    session.setAttribute(Constants.SK_REGIST_PHONE_KEY, phone);
                } catch (ClientException e) {
                }
            }
        }
        return rs;
    }


    @RequestMapping("/regist")
    @ResponseBody
    public JsonResponse regist(User user, Integer smsCode, Integer orgType, String orgName, String mzCode,Long enterpriseId, String enterpriseName, String enterpriseCode, Long minfeiId, String minfeiName, String minfeiCode, HttpSession session) {
        JsonResponse rs;
        Integer code = (Integer) session.getAttribute(Constants.SK_REGIST_PHONE_CODE_KEY);
        Long date = (Long) session.getAttribute(Constants.SK_REGIST_PHONE_CODE_KEY_DATE);
        String phone = (String) session.getAttribute(Constants.SK_REGIST_PHONE_KEY);
        if (null != code && smsCode.equals(code) && (System.currentTimeMillis() - date) <= (1000 * 60 * 15)) {
            user.setPhone(phone);
            Enterprise enterprise = new Enterprise(enterpriseId, enterpriseName, enterpriseCode);//企业
            MinfeiUnits minfeiUnits = new MinfeiUnits(minfeiId, minfeiName, minfeiCode);//民办企业
            Organization org = new Organization();//
            org.setName(orgName);
            org.setType(orgType);
            //根基民政侷的id查詢民政局
            MzDepartment mzDepartment = mzDepartmentService.selectByCode(mzCode);
            org.setMzName(mzDepartment.getDepartmentName());
            org.setMzCode(mzDepartment.getCode());
            org.setNature(Organization.NATURE_2);
            userService.regist(user, org, enterprise, minfeiUnits);
            rs = JsonResponse.success("注册成功！");
            session.removeAttribute(Constants.SK_REGIST_PHONE_CODE_KEY);
            session.removeAttribute(Constants.SK_REGIST_PHONE_CODE_KEY_DATE);
            session.removeAttribute(Constants.SK_REGIST_PHONE_KEY);
        } else {
            rs = JsonResponse.fail("验证码错误或失效！");
        }
        return rs;
    }

    @RequestMapping("/success")
    public String success() {
        return "registSuccess";
    }

    @RequestMapping("/privacy")
    public String privacy() {
        return "privacy";
    }

    /**
     * 检测某个企业是否存在
     *
     * @param code
     * @return
     */
    @RequestMapping("/enterprise")
    @ResponseBody
    public JsonResponse checkEnterprise(String code) {
        Enterprise enterprise = enterpriseService.selectOne(new EntityWrapper<Enterprise>().eq("code", code).eq("deleted", false));
        return JsonResponse.success(enterprise);
    }

    /**
     * 检测民非企业是否存在
     *
     * @param code
     * @return
     */
    @RequestMapping("/minfei")
    @ResponseBody
    public JsonResponse checkMinfei(String code) {
        MinfeiUnits minfeiUnits = minfeiUnitsService.selectOne(new EntityWrapper<MinfeiUnits>().eq("code", code).eq("deleted", false));
        return JsonResponse.success(minfeiUnits);
    }

    /**
     * 检测所有企业的名称是否冲突
     *
     * @param orgName
     * @return
     */
    @RequestMapping("/verifyExist")
    @ResponseBody
    public JsonResponse verifyExist(String orgName) {
        Organization organization = organizationService.selectOne(new EntityWrapper<Organization>().eq("name", orgName));
        log.debug("organization", organization);
        if (organization == null) {
            return new JsonResponse(200, "该机构没有被注册");
        } else {
            return new JsonResponse(0, "该机构已经被注册，请核对后从新输入");
        }
    }
}
